import pymysql

HOSTNAME = '127.0.0.1'
DATABASE = 'web_works'
PORT = 3306
USERNAME = 'root'
PASSWORD = '183492765'
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)

CONN = pymysql.connect(host=HOSTNAME, port=PORT, user=USERNAME, password=PASSWORD, database=DATABASE, charset='utf8mb4')

def con_my_sql(sql_code, params=None):
    try:
        CONN.ping(reconnect=True)

        #通过游标对象对数据库服务器发出sq1语句
        cursor = CONN.cursor(pymysql.cursors.DictCursor)
        cursor.execute(sql_code, params)

        CONN.commit()
        CONN.close()

        print('数据库连接成功')

        return cursor

    except pymysql.MySQLError as err_massage:
        print('数据库连接失败', err_massage)
        #回滚
        CONN.rollback()
        #关闭连接
        CONN.close()

        return type(err_massage), err_massage
